package com.jhs.kjs.robot.core;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.jhs.kjs.dto.CarDTO;
import com.jhs.kjs.dto.CarSensorDTO;
import com.jhs.kjs.model.daumMap.dto.DaumMapDTO;
import com.jhs.kjs.robot.service.ICoord2AddrService;
import com.jhs.kjs.robot.web.IConnectWeb;
import com.jhs.kjs.robot.web.IMakeUrl;

public enum ECoord2AddrBatch {
	MACHINE;

	private IMakeUrl urlMaker;
	private IConnectWeb connect;
	private ICoord2AddrService service;	
	
	private List<CarDTO> list;
	
	public void doJob() throws Exception, JSONException{
		String url = "";
		
		list = getNullOfAddressList();
		if(list!=null && list.size()>0){
			for(CarDTO c : list){
				url = urlMaker.getUrl(c.getLat().toString(), c.getLng().toString());
				if(url!=null){
					JSONObject json = connect.getJsonData(url);
					insertIntoBothCarNAddress(c, json);
				}
			}
		}else{
			
		}
	}
	
	public void makingPagingAddr(DaumMapDTO mapDto) throws Exception{
		try{
			String url=null;
			list = service.makingPagingAddr(mapDto);
			if(list!=null && list.size()>0){
				for(CarDTO c : list){
					url = urlMaker.getUrl(c.getLat().toString(), c.getLng().toString());
					if(url!=null){
						JSONObject json = connect.getJsonData(url);
						insertIntoBothPositionNAddress(c, json);
					}
				}
			}else{
				
			}
		}catch(Exception e){
			throw e;
		}
	}
	
	private void insertIntoBothPositionNAddress(CarDTO c, JSONObject json) throws Exception, JSONException  {
		c.setAddress(json.getString("fullName"));
		c.setAddressComponent1(json.getString("name1"));
		c.setAddressComponent2(json.getString("name2"));
		c.setAddressComponent3(json.getString("name3"));
		try{
			service.insertIntoCARPOSITIONADDR(c);	
		}catch(Exception e){ }
		
		
	}

	private void insertIntoBothCarNAddress(CarDTO car, JSONObject json) throws Exception, JSONException {
		car.setAddress(json.getString("fullName"));
		car.setAddressComponent1(json.getString("name1"));
		car.setAddressComponent2(json.getString("name2"));
		car.setAddressComponent3(json.getString("name3"));
		try{
			service.updateCAR(car);
			int cnt = service.checkCARPOSITIONADDRExsit(car);
			if(cnt!=1){
				service.insertIntoCARPOSITIONADDR(car);	
			}
			
			
		}catch(Exception e){}
		
		
	}

	public IMakeUrl getUrlMaker() {
		return urlMaker;
	}

	public void setUrlMaker(IMakeUrl urlMaker) {
		this.urlMaker = urlMaker;
	}

	public  void setCoord2AddrService(ICoord2AddrService service) {
		this.service = service;
	}


	public IConnectWeb getConnect() {
		return connect;
	}

	public void setConnect(IConnectWeb connect) {
		this.connect = connect;
	}

	private List<CarDTO> getNullOfAddressList() throws Exception {
		return service.getNullOfAddress();
	}

}
